#include "../include/Server.h"
#include <thread>
#include <netinet/in.h>
#include <unistd.h>
#include <string.h>

Server::Server():serverSocket(-1), _player(0), bStart(false)
{}
Server::~Server(){}

void Server::init()
{
    serverSocket = socket(AF_INET, SOCK_STREAM, 0);
    int opt = 1;
    setsockopt(serverSocket, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
    struct sockaddr_in serverAddr;
    serverAddr.sin_family = AF_INET;
    serverAddr.sin_addr.s_addr = htons(INADDR_ANY);
    serverAddr.sin_port = htons(8899);

    if(bind(serverSocket, (sockaddr*)&serverAddr, sizeof(serverAddr)) == -1)
    {
        perror("bind fail");
        return;
    }

    if(listen(serverSocket, 2) == -1)
    {
        perror("listen fail");
        return;
    }
}

void Server::readBuff()
{
    char buffer[128] = {'\0'};
    int player = 0;
    while(1)
    {
        memset(buffer, '\0', 128);
        if(recv(m_clients[player], buffer, 128, 0) <= 0)
        {
            std::cout << "server readBuff fail, quit" << std::endl;
            break;
        }
        else
        {
            std::cout << "server read: ";
            player = (int)buffer[2];
            std::cout << m_clients[player] << " send to socket: " << m_clients[player ^ 1] << std::endl;
            player ^= 1; 
            send(m_clients[player], buffer, sizeof(buffer), 0);
        } 
    }
}


void Server::start()
{
    while(true)
    {
        struct sockaddr_in clientAddr;
        socklen_t len;
        
        int clientSocket = accept(serverSocket, (sockaddr*)&clientAddr, &len);
        m_clients[_player] = clientSocket;
        _player++;
        if(clientSocket < 0)
        {
            std::cout << "client quit1" << endl;
            break;
        }
        cout << "the player :" << inet_ntoa(clientAddr.sin_addr) << "---" << clientSocket << " connect" << endl;
        
        if(_player == 2)
        {
            sendStart();
            break;
        }
    }
    std::cout << "game start" << std::endl;
    thread t1(&Server::readBuff, this);
    t1.join();
}

void Server::sendStart()
{
    //玩家1
    char buffer[128] = {'\0'};
    buffer[0] = 0;
    buffer[1] = 0;
    buffer[2] = 0;
    buffer[3] = 0;
    send(m_clients[0], buffer, sizeof(buffer), 0);

    //玩家2
    buffer[0] = 0;
    buffer[1] = 0;
    buffer[2] = 1;
    buffer[3] = 0;
    send(m_clients[1], buffer, sizeof(buffer), 0);

    bStart = true;
}

void Server::closeAll()
{
    close(serverSocket);
}

int main()
{
    Server *server = new Server();
    server->init();
    server->start();
    server->closeAll();
    return 0;
}

